<template>
  <div>
    <a-upload-dragger
      name="file"
      v-model:fileList="fileList"
      @change="onChange"
      multiple
      :action="getAction()"
      :maxCount="maxCount"
      :beforeUpload="beforeUpload"
      :directory="directory"
      :accept="accept"
      :showUploadList="showUploadList"
      :headers="{
        Authorization: `Bearer ${getToken()}`,
      }"
    >
      <slot>
        <p class="ant-upload-drag-icon">
          <inbox-outlined></inbox-outlined>
        </p>
        <p class="ant-upload-text">Click or drag file to this area to upload</p>
        <p class="ant-upload-hint">将文件拖入此处进行上传</p>
      </slot>
    </a-upload-dragger>
  </div>
</template>

<script setup lang="ts">
import { uploadFile } from '@/api/modules/utils/files';
import { getToken } from '@/store/user/utils';
import { joinUrl } from '@/utils/file/format';
import type { UploadFile } from 'ant-design-vue';
import type { UploadRequestOption } from 'ant-design-vue/es/vc-upload/interface';

const uri = defineModel('uri');
interface FileUpload {
  /* 文件上传到服务器指定的name */
  name?: string;
  /*
    最大数量,
    使用maxCount来限制单文件上传，或多文件上传
  */
  maxCount?: number;
  /* 允许上传文件夹 */
  directory?: boolean;
  /* 预览文件列表 */
  fileList?: UploadFile[];
  /* 接受的类型 */
  accept?: string;
  showUploadList?: boolean;
  beforeUpload?: any;
  url?: string;
}
/* 文件列表,上传到本地的文件和上传到服务器的文件 */
const fileList = ref<UploadFile[]>([]);
const emit = defineEmits(['change', 'update:fileList']);

const props = withDefaults(defineProps<FileUpload>(), {
  name: 'file',
  showUploadList: true,
});
const getAction = () => {
  return joinUrl(import.meta.env.VITE_BASEURL, joinUrl(`/v2/sys/api/upload`, props.url!));
};
const onChange = async () => {
  const { data } = await uploadFile({
    file: fileList.value[0].originFileObj!,
    url: '',
  });

  emit('change', data.data);
  uri.value = data.data;
};
</script>

<style lang="scss" scoped></style>
